from django.db import models
from django.db.models import signals
from django.contrib.contenttypes import generic
from django.contrib.auth.models import User
from django.template.defaultfilters import slugify

from events.models import timeline_updater, TimeLine

class Project(models.Model):
    title = models.CharField(max_length=50)
    slug = models.SlugField(unique=True, editable=False)
    description = models.TextField()
    url = models.URLField(blank=True)
    private = models.BooleanField(default=False)
    members = models.ManyToManyField(User, through="Membership")
    creator = models.ForeignKey(User, related_name='created_projects', editable=False)
    events = generic.GenericRelation(TimeLine, related_name='projects')
    date_added = models.DateTimeField(auto_now_add=True)
    date_modified = models.DateTimeField(auto_now=True)

    def __unicode__(self):
        return self.title

    def save(self, **kwargs):
        if self.id is None:
            self.slug = slugify(self.title)
        return super(Project, self).save()

    @models.permalink
    def get_absolute_url(self):
        return ('project_detail', [self.slug])

    @property
    def project(self):
        return self

class Membership(models.Model):
    user = models.ForeignKey(User)
    project = models.ForeignKey(Project)
    joined_at = models.DateTimeField(auto_now_add=True)

# Signals
signals.post_save.connect(timeline_updater, sender=Project)
